package com.csdj.s3project.controller;


import com.csdj.s3project.common.CacheConstant;
import com.csdj.s3project.common.StatusContant;
import com.csdj.s3project.common.WebResult;
import com.csdj.s3project.common.WebResultMsgCode;
import com.csdj.s3project.entity.User;
import com.csdj.s3project.service.IIntegralRecordService;
import com.csdj.s3project.service.IUserService;
import com.csdj.s3project.service.RedisService;
import com.csdj.s3project.utils.UpPhotoNameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author zq
 * @since 2022-02-04
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    private Logger log = LoggerFactory.getLogger("userController");
    @Resource
    private IUserService iUserService;
    @Resource
    private RedisService redisService;
    @Resource
    private IIntegralRecordService iIntegralRecordService;

    //文件上传路径
    @Value("${file.upload.url}")
    private String uploadUrl;
    //服务器路径前缀
    @Value("${file.upload.prefix-url}")
    private String prefixUrl;
    //默认头像路径
    @Value("${file.upload.default-profile-photo}")
    private String defaultProfilePhoto;


    @PostMapping("/login")
    public WebResult login(@RequestParam String account,
                           @RequestParam String password) {
        User user = iUserService.login(account, password);
        if (user != null && StatusContant.USER_STATUS_LOCKED == user.getStatus()) {
            return new WebResult(WebResultMsgCode.USER_LOCKED);
        }
        if (user == null) {
            return new WebResult(WebResultMsgCode.USER_PWD_ERROR);
        }
        return new WebResult(WebResultMsgCode.SUCCESS).putData("user", user);
    }


    @GetMapping("/show/personalinfo")
    public WebResult showPersonalInfo(HttpServletRequest request) {
        int uid = getUid(request);
        log.info("id:" + uid);
        User userInfo = iUserService.selectUserInfo(uid);
        log.info(userInfo.toString());
        if (userInfo == null) {
            return new WebResult().putData("user", null);
        }
        return new WebResult().putData("user", userInfo);
    }


    @GetMapping("/update/personalinfo")
    public WebResult updatePersonalInfo(User user) {
        log.info("用户想要更新的参数为:" + user);
        int result = iUserService.updatePersonalInfo(user);
        log.info("更新的返回结果:" + result);
        if (result == 0) {
            return new WebResult(WebResultMsgCode.FAIL);
        }
        return new WebResult(WebResultMsgCode.SUCCESS).putData("user", result);
    }


    @GetMapping("/regemail")
    public WebResult selectEmail(@RequestParam String email) {
        boolean result = iUserService.selectEmail(email);
        //log.info(String.valueOf(result));
        if (result == false) {
            return new WebResult(WebResultMsgCode.FAIL);
        }
        return new WebResult(WebResultMsgCode.SUCCESS).putData("user", result);
    }


    @GetMapping("headpicture")
    public WebResult selectUserPicture(@RequestParam int id) {
        User userInfo = iUserService.selectUserInfo(id);
        log.info(userInfo.toString());
        if (userInfo == null) {
            return new WebResult().putData("user", null);
        }
        return new WebResult().putData("user", userInfo);
    }


    @GetMapping("/register")
    public WebResult register(@RequestParam String account, @RequestParam String password, @RequestParam String email, @RequestParam String checkCode,
                              @RequestParam(required = false) String superiorInvitation) {
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        user.setEmail(email);
        log.info(user.toString());
        log.info(checkCode);

        //核对验证码
        //log.info(redisService.getObject(CacheConstant.TOKEN_PREFIX + user.getAccount()));
        if (!checkCode.equals(redisService.getObject(CacheConstant.TOKEN_PREFIX + user.getAccount()))) {
            return new WebResult(WebResultMsgCode.FAIL).putData("check", 1);
        }

        if(StringUtils.hasText(superiorInvitation)){
            //查询邀请码
            int userId = iUserService.selectUser(superiorInvitation);
            log.info(String.valueOf(userId));
            if (userId == 0) {
                return new WebResult(WebResultMsgCode.FAIL).putData("superior", 1);
            }
            //邀请码正确后给对应id的上级用户加20积分
            User selectIntegral = iUserService.selectUserInfo(userId);
            log.info("查询上级用户信息:" + selectIntegral);
            //将上级用户的邮箱账号传入新增用户的对象里
            user.setSuperiorUser(selectIntegral.getAccount());
            int jieguo = iUserService.updateSuperiorUser(selectIntegral);
            log.info("更新:" + jieguo);
            if (jieguo == 0) {
                return new WebResult(WebResultMsgCode.FAIL).putData("updateSuperiorUser", 1);
            }
            //邀请新用户注册成功后给上级用户积分记录表插入一条记录
            int record = iIntegralRecordService.insertIntegralRecordById(userId, "邀请新用户", selectIntegral.getIntegral());
        }

        log.info("最终注册的用户信息:" + user);
        //进行注册
        int result = iUserService.register(user);
        if (result == 0) {
            return new WebResult(WebResultMsgCode.FAIL);
        }
        User self = iUserService.login(account, password);
        log.info("注册时被送积分的新用户的id:"+self.getId());
        //注册成功后给积分记录表插入一条记录
        int record = iIntegralRecordService.insertIntegralRecordById(self.getId(), "注册账号", 10);
        return new WebResult(WebResultMsgCode.SUCCESS).putData("user", result);
    }


    /**
     * 上传头像, 修改头像
     * @param file 文件上传工具类
     * @param request http请求
     * @return
     */
    @PostMapping("/upload")
    public WebResult updoadHeadUrl(@RequestParam("file") MultipartFile file,
                                   HttpServletRequest request) {

        int id = getUid(request);
        log.info("id:" + id);
        //@RequestParam("file") MultipartFile file为接收图片参数
        //Integer userId,String status 用户Id和状态

        try {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            log.info("imageFileName:"+imageFileName);

            String fileName = UpPhotoNameUtils.getPhotoName("img",imageFileName);
            log.info("fileName:"+fileName);
            //"F:/学习/S2项目图片素材"为本地目录
            //路径切记不要写死,要引用配置文件里的
            Path path = Paths.get(uploadUrl + fileName);
            //将上传图片路径写入文件
            Files.write(path,bytes);
            //将图片服务器路径前缀+图片名称写入数据库
            //路径切记不要写死,要引用配置文件里的
            log.info("prefixUrl:"+prefixUrl);
            String avatarUrl = prefixUrl + fileName;
            log.info("avatarUrl:"+avatarUrl);
            User user = new User();
            user.setId(id);
            //头像
            user.setHeadUrl(avatarUrl);
            //修改用户头像
            iUserService.updatePersonalInfo(user);
            //返回文件名字
            return new WebResult(WebResultMsgCode.SUCCESS).putData("filename", fileName);
        } catch (IOException e) {
            //e.printStackTrace();
            log.error("error: "+e.getMessage());
        }
        return new WebResult(WebResultMsgCode.FAIL);
    }


}
